﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Mogubang_Sl.Entity;
using Mogubang_Sl.Core;
using Mogubang_Sl.Utils;
using OpenXLive.Features;
using OpenXLive;
using Microsoft.Phone.Tasks;
using System.Windows.Threading;
using System.Windows.Media.Imaging;

namespace Mogubang_Sl.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance = null;

        /// <summary>
        /// 当前状态 0-未初始化 1-进行中 2-暂停 3-结束 4-结束动画进行中
        /// </summary>
        public int currStatus = 0;
        public int currLife = 0;
        public int currScore = 0;

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 2;

        public GamePage()
        {
            InitializeComponent();
            currStatus = 0;
            Instance = this;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (currStatus == 1)
            {
                //暂停
                currStatus = 2;
                this.StoryboardShowPause.Begin();

                this.btnMusic.IsChecked = StageManager.Instance.IsPlayBackground;
                this.btnSound.IsChecked = StageManager.Instance.IsPlaySound;
            }
            else if (currStatus == 2)
            {
                //继续游戏
                currStatus = 1;
                this.StoryboardHidePause.Begin();
            }
            else if (currStatus == 3)
            {
                //返回主界面
                if (this.NavigationService.CanGoBack)
                {
                    this.NavigationService.GoBack();
                }
                else
                {
                    this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
                }
            }
            e.Cancel = true;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (StageManager.Instance.IsPlayBackground)
            {
                AudioPlayHelper.PlayBackground();
            }
            if (currStatus == 0)
            {
                string isNewGame = "1";
                NavigationContext.QueryString.TryGetValue("isNewGame", out isNewGame);

                if (isNewGame == "1")
                {
                    //新游戏
                    StartNewGame();
                    currStatus = 1;
                }
                else
                {
                    //继续上次的进度
                    ContinueGame();
                    currStatus = 1;
                }
            }

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();

            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    gridAd.Children.Remove(imgBanner);
                    gridAd.Children.Add(imgBanner);
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
            }
        }


        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //保存游戏进度
            if (currStatus == 1 || currStatus == 2)
            {
                LastStageInfo info = new LastStageInfo();
                info.CurrentScore = currScore;
                info.LeftLifeCount = currLife;
                info.moguDatas = this.gameCanvas.GetGameData();

                StageManager.Instance.LastStage = info;
            }
            else if (currStatus == 3)
            {
                //清除游戏数据
                StageManager.Instance.LastStage = null;
            }

        }

        private void ContinueGame()
        {
            this.gameCanvas.ContinueGame();
            if (StageManager.Instance.LastStage != null)
            {
                this.currScore = StageManager.Instance.LastStage.CurrentScore;
                this.currLife = StageManager.Instance.LastStage.LeftLifeCount;

                UpdateStatusUI();
            }
            this.StoryboardStartGame.BeginTime = TimeSpan.FromSeconds(1);
            this.StoryboardStartGame.Begin();
        }


        private void StartNewGame()
        {
            this.gameCanvas.StartNew();

            this.currScore = 0;
            this.currLife = GameStatics.DefaultLife;

            UpdateStatusUI();

            if (StageManager.Instance.IsFirstGame)
            {
                this.imgGuide.Visibility = System.Windows.Visibility.Visible;
            }
            this.StoryboardStartGame.BeginTime = TimeSpan.FromSeconds(1);
            this.StoryboardStartGame.Begin();
        }

        private void btnRearrange_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            //重排
            this.gameCanvas.Rearrange();
        }

        private void btnWood_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            if (StageManager.Instance.WoodCount > 0)
            {
                //木材
                this.gameCanvas.UseWood();
            }
            else
            {
                MessageBox.Show("木材块道具数量不足，通过合成树木来获取该道具。");
            }
        }

        private void btnBomb_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            if (StageManager.Instance.BombCount > 0)
            {
                //炸弹
                this.gameCanvas.UseBomb();
            }
            else
            {
                MessageBox.Show("炸弹块道具数量不足，通过合成有毒的花来获取该道具。");
            }
        }

        private void btnPause_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            if (currStatus == 1)
            {
                //暂停
                currStatus = 2;
                this.StoryboardShowPause.Begin();

                this.btnMusic.IsChecked = StageManager.Instance.IsPlayBackground;
                this.btnSound.IsChecked = StageManager.Instance.IsPlaySound;
            }
        }

        internal void UpdateStatusUI()
        {
            //更新界面
            this.txtLife.Text = this.currLife.ToString();
            this.txtScore.Text = this.currScore.ToString();
            this.txtCoinCount.Text = StageManager.Instance.TotalG.ToString();

            this.txtBombCount.Text = StageManager.Instance.BombCount.ToString();
            this.txtWoodCount.Text = StageManager.Instance.WoodCount.ToString();
        }

        internal void AddScore(int score, int life, int combo)
        {
            this.currScore += score;
            this.currLife += life;
            UpdateStatusUI();
            this.scoreView.AddScore(score, life, combo);
        }

        /// <summary>
        /// 减少生命
        /// </summary>
        internal void SubGameLife()
        {
            this.currLife--;
            UpdateStatusUI();
        }

        /// <summary>
        /// 用完所有的生命
        /// </summary>
        internal void FinishGame()
        {
            SoundManager.PlayEffect(SoundManager.gameover);
            currStatus = 4;
            if (currScore > StageManager.Instance.HighScore)
            {
                StageManager.Instance.HighScore = currScore;
                this.imgCompleteNewHigh.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                this.imgCompleteNewHigh.Visibility = System.Windows.Visibility.Collapsed;
            }
            this.txtCompleteScore.Text = currScore.ToString();
            int addCoin = MoguDataHelper.GetAddCoinCount(currScore);
            this.txtCompleteCoin.Text = addCoin.ToString();
            StageManager.Instance.TotalG += addCoin;
            this.StoryboardShowComplete.Completed += StoryboardShowComplete_Completed;
            this.StoryboardShowComplete.Begin();

            //上传分数至排行榜
            if (XLiveGameManager.CurrentSession != null && XLiveGameManager.CurrentSession.IsValid)
            {
                Leaderboard lb = new Leaderboard(XLiveGameManager.CurrentSession, "d8891075-9d02-4e1e-bd37-3e0155a00471");
                lb.SubmitScoreCompleted += lb_SubmitScoreCompleted;
                lb.SubmitScore(currScore);
            }
        }

        void lb_SubmitScoreCompleted(object sender, OpenXLive.AsyncEventArgs e)
        {

        }

        void StoryboardShowComplete_Completed(object sender, EventArgs e)
        {
            currStatus = 3;
        }

        private void btnResume_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            if (currStatus == 2)
            {
                //继续游戏
                currStatus = 1;
                this.StoryboardHidePause.Begin();
            }
        }

        private void btnMainMenu_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            //返回主界面
            if (this.NavigationService.CanGoBack)
            {
                this.NavigationService.GoBack();
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private void btnSound_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            StageManager.Instance.IsPlaySound = this.btnSound.IsChecked.Value;
            SoundManager.PlayEffect(SoundManager.clickbutton);
        }

        private void btnMusic_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.clickbutton);
            StageManager.Instance.IsPlayBackground = this.btnMusic.IsChecked.Value;
            if (StageManager.Instance.IsPlayBackground)
            {
                AudioPlayHelper.PlayBackground();
            }
            else
            {
                AudioPlayHelper.StopBackground();
            }
        }

        private void imgGuide_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //游戏教程图片点击事件
            StageManager.Instance.IsFirstGame = false;
            this.imgGuide.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void imgBanner_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }
    }
}